<template>
  <el-dialog
    v-model="isShow"
    draggable
    :width="720"
    :close-on-click-modal="false"
    :before-close="close"
  >
    <template #header>
      {{ data.title }}
    </template>
    <el-form :model="data">
      <div class="form-item-row">
        <el-form-item label="固件名称" :label-width="sLabel[0]">
          <el-input
            v-model="data.firmware_name"
            :disabled="data.flag == 'del'"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-tag
            :type="data.status == 0 ? 'success' : 'danger'"
            style="margin: 0 5px"
            >{{ data.status }}</el-tag
          >
        </el-form-item> -->
      </div>
      <el-form-item label="命名规则" :label-width="sLabel[0]">
        <el-tag
          >主板型号加显示屏类型加固件日期等信息组成，例如：Z3581双EDP1366*768@20230926</el-tag
        >
      </el-form-item>
      <el-form-item label="固件文件名" :label-width="sLabel[0]">
        <el-input
          v-model="data.firmware_file_name"
          :disabled="data.flag == 'del'"
          style="width: 450px"
        ></el-input>
      </el-form-item>
      <el-form-item label="选择主板型号" :label-width="sLabel[0]">
        <el-select
          v-model="boardValue"
          filterable
          remote
          reserve-keyword
          placeholder="输入主板型号关键字查询"
          remote-show-suffix
          @click="getBoard('')"
          :remote-method="getBoard"
          :loading="loading"
          @change="boardChange"
          :disabled="data.flag == 'del'"
        >
          <el-option
            v-for="item in boardOptions"
            :key="item.Id"
            :label="item.model"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <div class="form-item-row" v-if="!isNull(boardValue)">
        <el-form-item label="主板型号" :label-width="sLabel[0]">
          <el-tag type="error" size="large" style="font-size: 14px">{{
            data.board.model
          }}</el-tag>
        </el-form-item>
        <el-form-item label="主板厂商" :label-width="sLabel[1]">
          <el-tag type="warning" size="large" style="font-size: 14px">{{
            data.board.factory.factory
          }}</el-tag>
        </el-form-item>
      </div>
      <el-form-item label="固件版本" :label-width="sLabel[0]">
        <el-popover
          placement="bottom-start"
          :offset="5"
          :width="800"
          trigger="click"
        >
          <template #reference>
            <el-tag type="success" size="large" style="cursor: pointer">
              已有<el-text size="large" tag="b">{{
                editionInfos.length
              }}</el-text
              >个版本,点击设置固件版本
            </el-tag>
          </template>
          <template #default>
            <div class="rom-version">
              <div
                class="item"
                v-for="item in editionInfos"
                :key="item.version"
              >
                <el-tag
                  size="large"
                  class="code"
                  @click="setVersion('hit', item.version)"
                >
                  {{ item.version }}
                </el-tag>
                <el-tooltip
                  effect="dark"
                  :content="item.edition"
                  placement="top"
                >
                  <el-tag size="large" type="success" class="name">
                    <el-text truncated>{{ item.edition }}</el-text>
                  </el-tag>
                </el-tooltip>
                <el-tooltip effect="dark" :content="item.url" placement="top">
                  <el-tag size="large" type="danger" class="name">
                    <el-text truncated>{{ item.url }}</el-text>
                  </el-tag>
                </el-tooltip>
                <el-tooltip
                  effect="dark"
                  :content="item.remark"
                  placement="top"
                >
                  <el-tag size="large" type="info" class="name">
                    <el-text truncated>{{ item.remark }}</el-text>
                  </el-tag>
                </el-tooltip>
                <el-button
                  type="danger"
                  circle
                  plain
                  @click="setVersion('del', item.version)"
                  class="btn"
                >
                  <i class="iconfont icon-shanchu"></i>
                </el-button>
              </div>
              <div class="item">
                <el-input
                  v-model="verInput.version"
                  placeholder="版本号"
                  class="code"
                />
                <el-input
                  v-model="verInput.edition"
                  placeholder="版本名称"
                  class="name"
                />
                <el-input
                  v-model="verInput.url"
                  placeholder="固件下载地址"
                  class="name"
                />
                <el-input
                  v-model="verInput.remark"
                  placeholder="版本说明"
                  class="name"
                />
                <el-button
                  type="success"
                  circle
                  plain
                  @click="setVersion('set', verInput.version)"
                  class="btn"
                >
                  <i class="iconfont icon-queren"></i>
                </el-button>
              </div>
            </div>
          </template>
        </el-popover>
      </el-form-item>
      <div class="form-item-row" v-if="data.dtCreate != ''">
        <el-form-item label="创建时间" :label-width="sLabel[0]">
          <span class="label">{{ data.dtCreate }}</span>
        </el-form-item>
        <el-form-item label="操作员" :label-width="sLabel[1]">
          <span class="label">{{ data.operCreate }}</span>
        </el-form-item>
      </div>
      <div class="form-item-row" v-if="data.dtUpdate != ''">
        <el-form-item label="修改时间" :label-width="sLabel[0]">
          <span class="label">{{ data.dtUpdate }}</span>
        </el-form-item>
        <el-form-item label="操作员" :label-width="sLabel[1]">
          <span class="label">{{ data.operUpdate }}</span>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="close()">取 消</el-button>
        <el-button
          v-if="data.flag == 'del'"
          type="danger"
          @click="
            msgBox(
              'status',
              data.status == cStatus[0] ? '停用此固件' : '取消停用'
            )
          "
          >{{ data.status == cStatus[0] ? "停 用" : "取消停用" }}</el-button
        >
        <el-button v-else type="primary" @click="done()" :loading="loading"
          >确 定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, reactive, ref } from "vue-demi";
import http from "@/axios/http";
import util from "@/assets/js/util";
import { ElMessageBox, ElNotification } from "element-plus";
import mqtt from "@/assets/js/mqtt";
export default {
  setup(props, ctx) {
    const Global = getCurrentInstance().proxy;
    let user = reactive({
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      power: Global.$var.user.power,
    });

    function mqttOnMsg() {
      mqtt.onMsg((t, m) => {
        loading.value = false;
        let r = JSON.parse(m);
        if (r.data.returnCode == 10000) {
          let d = r.data.data;
          if (r.msgType == 150 || r.msgType == 152) {
          //console.log(d)
            ctx.emit("done", data);
            isShow.value = false;
          }
          if (r.msgType == 145) {
            boardOptions.value = d;
          }
        }
      });
    }

    let cStatus = ref(Global.$const.STATUS_DATA);
    let sLabel = ref(["150px", "80px", "450px"]);
    let verInput = reactive({
      version: "",
      edition: "",
      url: "",
      remark: "",
    });
    let isShow = ref(false);
    let data = reactive({
      flag: "",
      title: "",
      id: "",
      firmware_name: "",
      firmware_file_name: "",
      board: {},
      board_id: "",
      dtCreate: "",
      operCreate: "",
      dtUpdate: "",
      operUpdate: "",
    });
    let loading = ref(false);
    function open(d) {
    //console.log(d);
      mqttOnMsg();
      boardValue.value = "";
      editionInfos.value = []
      data.flag = d.flag;
      if (d.flag == "add") {
        data.title = "新建固件";
        data.id = "";
        data.firmware_name = "";
        data.firmware_file_name = "";
        data.board = {};
        data.board_id = "";
        // data.dtCreate = "";
        // data.operCreate = "";
        // data.dtUpdate = "";
        // data.operUpdate = "";
      } else {
        data.title = d.flag == "del" ? "固件状态" : "编辑固件";
        data.id = d.Id;
        data.firmware_name = d.firmware_name;
        data.firmware_file_name = d.firmware_file_name;
        data.board = d.board;
        boardValue.value = d.board.model;
        data.board_id = d.board_id;
        let eid = d.edition_infos
        editionInfos.value = eid;
        // data.dtCreate = d.dtCreate;
        // data.operCreate = d.operCreate;
        // data.dtUpdate = d.dtUpdate;
        // data.operUpdate = d.operUpdate;
      }
      clear();
      isShow.value = true;
    }
    function close() {
      ctx.emit("done", '');
      isShow.value = false;
    }
    function done() {
      let err = "";
      if (util.isNull(data.firmware_name)) err = "固件名称不能为空";
      else if (util.isNull(data.board)) err = "请选择主板型号";
      else if (
        util.isNull(editionInfos.value) ||
        util.isNull(editionInfos.value[0].url)
      )
        err = "固件版本不能为空";
      if (!util.isNull(err)) {
        ElNotification({
          type: "warning",
          duration: 1500,
          title: "",
          message: err,
        });
        return;
      }
      loading.value = true;
      if (data.flag == "add" || data.flag == "edit") {
        let msgCode = 150;
        if (data.flag == "edit") msgCode = 152;
        let topic = mqtt.TOPIC_REQ + msgCode;
        let p = {};
        p.msgType = msgCode;
        p.clientId = user.id;
        p.userName = user.username;
        let m = {};
        if (data.flag == "edit") m.Id = data.id
        m.firmware_name = data.firmware_name
        m.firmware_model = data.firmware_name
        m.firmware_file_name = data.firmware_file_name
        m.firmware_remark = ''
        m.board_id = data.board.Id
        m.edition_infos = editionInfos.value
        p.message = {}
        p.message.firmware = JSON.stringify(m)
      //console.log('固件编辑：',JSON.stringify(p))
        mqtt.publish(topic,JSON.stringify(p))
      }
    }
    // 确认msgBox
    function msgBox(flag, msg, title = "是否确认？", cbt = "确认") {
      ElMessageBox.confirm(msg, title, {
        confirmButtonText: cbt,
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (flag == "status") done();
        })
        .catch(() => {});
    }
    // 设置固件版本
    let editionInfos = ref([])
    function setVersion(f, version) {
      let v = {};
      v.version = verInput.version;
      v.edition = verInput.edition;
      v.url = verInput.url;
      v.remark = verInput.remark;
      if (f=='set') {
        if (isNull(v.version) || isNull(v.edition) || isNull(v.url)) {
          ElNotification({
            type: "warning",
            duration: 1500,
            title: "",
            message: '需要填写版本号、版本名称和下载地址',
          });
          return
        }
      }

      let eiData = editionInfos.value;
      let index = -1
      for (let i in eiData) {
        if (eiData[i].version == version) {
          index = i
        }
      }

      if (index < 0) {
        if (f=='set') {
          if (eiData.length >= 6) {
            ElNotification({
              type: "warning",
              title: "新增固件版本失败",
              message: "最多只能添加6个版本",
            });
          } else {
            eiData.push(v);
            clear();
          }
        }
      } else {
        if (f=='set') {
          eiData[index].version = verInput.version;
          eiData[index].edition = verInput.edition;
          eiData[index].url = verInput.url;
          eiData[index].remark = verInput.remark;
        }
        if (f == "hit") {
          verInput.version = eiData[index].version;
          verInput.edition = eiData[index].edition;
          verInput.url = eiData[index].url;
          verInput.remark = eiData[index].remark;
        }
        if (f == "del") {
          eiData.splice(index,1)
        }
      }
      editionInfos.value = eiData
    }
    function clear() {
      verInput.version = "";
      verInput.edition = "";
      verInput.url = "";
      verInput.remark = "";
    }
    // 查询主板型号
    let boardValue = ref("");
    let boardOptions = ref([]);
    function getBoard(query) {
      let msgCode = 145;
      let topic = mqtt.TOPIC_REQ + msgCode;
      let g = {};
      g.msgType = msgCode;
      g.clientId = user.id;
      g.userName = user.username;
      let m = {};
      m.firmware_name = query
      m.factory = ''
      m.model = ''
      m.edition = ''
      m.version = ''
      m.status = 0
      m.indexPage = 1;
      m.pageSize = 10;
      g.message = m;
      mqtt.publish(topic, JSON.stringify(g));
    }
    function boardChange(e) {
      let bo = boardOptions.value;
      for (let i in bo) {
        if (e == bo[i].Id) {
          data.board = bo[i];
        }
      }   
    }

    function isNull(v) {
      return util.isNull(v);
    }

    return {
      user,
      cStatus,
      sLabel,
      verInput,
      isShow,
      data,
      loading,
      open,
      close,
      done,
      msgBox,
      editionInfos,
      setVersion,
      boardValue,
      boardOptions,
      getBoard,
      boardChange,
      isNull,
    };
  },
};
</script>

<style lang="scss" scoped>
.form-item-row {
  display: flex;
  flex-direction: row;
  .label {
    background-color: $color-primary-away;
    // border: 1px solid $color-primary-light;
    padding: 0px 15px;
    border-radius: 1px;
  }
}
.rom-version {
  .item {
    display: flex;
    flex-direction: row;
    .code {
      width: 100px;
      margin-top: 5px;
      margin-right: 5px;
      cursor: pointer;
    }
    .name {
      width: 200px;
      margin-top: 5px;
      margin-right: 5px;
      .el-text {
        width: 180px;
      }
    }
    .btn {
      margin-top: 5px;
      margin-left: 5px;
    }
  }
}
</style>